package io.terminus.spzx.product.service.impl;

import com.alibaba.fastjson.JSON;
import io.terminus.spzx.model.entity.product.Category;
import io.terminus.spzx.product.mapper.CategoryMapper;
import io.terminus.spzx.product.service.CategoryService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author lichunlong lcl253137@alibaba-inc.com
 * @Desc 移动端分类管理Service实现类
 * @Date 2024-10-20
 */
@Service
@RequiredArgsConstructor
public class CategoryServiceImpl implements CategoryService {

    private final RedisTemplate<String, String> redisTemplate;

    private final CategoryMapper categoryMapper;

    @Override
    public List<Category> findOneCategory() {
        List<Category> categoryList;
        String categoryListJson = redisTemplate.opsForValue().get("category:one");

        if (StringUtils.isEmpty(categoryListJson)) {
            categoryList = categoryMapper.findOneCategory();
            categoryListJson = JSON.toJSONString(categoryList);

            redisTemplate.opsForValue().set("category:one", categoryListJson, 7, TimeUnit.DAYS);
        }
        categoryList = JSON.parseArray(categoryListJson, Category.class);

        return categoryList;
    }

    @Override
    @Cacheable(value = "category" , key = "'all'")
    public List<Category> findCategoryTree() {
        List<Category> categoryList = categoryMapper.findAll();
        //全部一级分类
        List<Category> firstCategoryList = categoryList.stream().filter(item -> item.getParentId() == 0).toList();
        if (CollectionUtils.isNotEmpty(firstCategoryList)) {
            firstCategoryList.forEach(firstCategory -> {
                List<Category> secondCategoryList = categoryList.stream().filter(item -> item.getParentId().longValue() == firstCategory.getId().longValue()).collect(Collectors.toList());
                firstCategory.setChildren(secondCategoryList);

                if (CollectionUtils.isNotEmpty(secondCategoryList)) {
                    secondCategoryList.forEach(secondCategory -> {
                        List<Category> thirdCategoryList = categoryList.stream().filter(item -> item.getParentId().longValue() == secondCategory.getId().longValue()).collect(Collectors.toList());
                        secondCategory.setChildren(thirdCategoryList);
                    });
                }
            });
        }
        return firstCategoryList;
    }
}
